import _ from 'lodash';


/** leading为true时，表示点击后立即调用  */
export const debounce = (fn, wait = 2000, configObj = { leading: false, trailing: true }) => _.debounce(fn, wait, configObj)
export const delayedRequest = (requestFunction:any,timeout=5000) => {
  let firstRequestTimestamp: any = null;
  let lastRequestTimestamp: any = null;
  const debounceFn = debounce(()=>{
     firstRequestTimestamp = null
     // console.log('最后一次是不是@@@');
     return requestFunction()
  },timeout)
  function executeRequest() {
     // 获取当前请求的时间戳
     const currentTimestamp = Date.now();
     firstRequestTimestamp = currentTimestamp-firstRequestTimestamp>6000?null:currentTimestamp
     // 如果这是第一次请求，则记录下时间戳并执行请求方法
     if (firstRequestTimestamp === null) {
        // console.log('第一次执行吗');
        firstRequestTimestamp = currentTimestamp;
        requestFunction();
     }else{
        debounceFn()
     }
     // // 记录每次请求的时间戳，用于更新最后一次请求的时间戳
     // lastRequestTimestamp = currentTimestamp;
     // // 使用 setTimeout() 设置延迟一秒后执行最后一次请求方法
     // setTimeout(() => {
     //    // 检查当前请求是否为最后一次请求
     //    if (currentTimestamp === lastRequestTimestamp) {
     //       console.log('最后一次吗s');
     //       requestFunction();
     //    }
     // }, timeout);
  }

  return executeRequest;
}
export const delayedRequests = (requestFunction, timeout = 5000) => {
  let firstRequestTimestamp: number | null = null;
  const debounceFn = debounce(() => {
     firstRequestTimestamp = null;
     return requestFunction();
  }, timeout);

  function executeRequest() {
     const currentTimestamp = Date.now();

     // 如果超过6秒或者是第一次，重置状态
     if (firstRequestTimestamp === null ||
         currentTimestamp - firstRequestTimestamp > 6000) {
        firstRequestTimestamp = currentTimestamp;
        requestFunction();
     } else {
        debounceFn();
     }
  }

  return executeRequest;
};
